package com.jn.zhinongbao.adapter.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.supportingagriculturaltreasures.CartActivity;
import com.example.supportingagriculturaltreasures.LoginActivity;
import com.example.supportingagriculturaltreasures.MainActivity;
import com.example.supportingagriculturaltreasures.MerchantActivity;
import com.example.supportingagriculturaltreasures.OrderActivity;
import com.example.supportingagriculturaltreasures.R;
import com.example.supportingagriculturaltreasures.bean.User;
import com.example.supportingagriculturaltreasures.database.DatabaseHelper;
import com.example.supportingagriculturaltreasures.utils.PreferenceManager;

public class ProfileFragment extends Fragment {

    private TextView tvUsername, tvPhone, tvRole, tvShopName;
    private LinearLayout llShopInfo, llCart, llOrders, llSettings, llHome, llProfile;
    private ImageView ivAvatar;
    
    private PreferenceManager preferenceManager;
    private DatabaseHelper databaseHelper;
    private User currentUser;

    public static ProfileFragment newInstance() {
        return new ProfileFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        initViews(view);
        initData();
        loadUserData();
        setupClickListeners();
    }

    private void initViews(View view) {
        ivAvatar = view.findViewById(R.id.iv_avatar);
        tvUsername = view.findViewById(R.id.tv_username);
        tvPhone = view.findViewById(R.id.tv_phone);
        tvRole = view.findViewById(R.id.tv_role);
        tvShopName = view.findViewById(R.id.tv_shop_name);
        llShopInfo = view.findViewById(R.id.ll_shop_info);
        llHome = view.findViewById(R.id.ll_home);
        llProfile = view.findViewById(R.id.ll_profile);
        llCart = view.findViewById(R.id.ll_cart);
        llOrders = view.findViewById(R.id.ll_orders);
        llSettings = view.findViewById(R.id.ll_settings);
    }

    private void initData() {
        preferenceManager = new PreferenceManager(requireContext());
        databaseHelper = new DatabaseHelper(requireContext());
    }

    private void loadUserData() {
        int userId = preferenceManager.getCurrentUserId();
        if (userId != -1) {
            currentUser = databaseHelper.getUserById(userId);
            if (currentUser != null) {
                displayUserInfo();
            } else {
                Toast.makeText(requireContext(), "用户信息获取失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void displayUserInfo() {
        if (currentUser != null) {
            tvUsername.setText(currentUser.getUsername());
            tvPhone.setText(currentUser.getPhone());
            tvRole.setText(currentUser.getRoleText());
            
            // 如果是商家，显示店铺信息
            if (currentUser.isMerchant() && currentUser.getShopName() != null) {
                llShopInfo.setVisibility(View.VISIBLE);
                tvShopName.setText(currentUser.getShopName());
            } else {
                llShopInfo.setVisibility(View.GONE);
            }
        }
    }

    private void setupClickListeners() {
        llHome.setOnClickListener(v -> {
            // 切换到主页
            if (getActivity() instanceof MainActivity) {
                ((MainActivity) getActivity()).findViewById(R.id.bottom_navigation).findViewById(R.id.nav_home).performClick();
            } else if (getActivity() instanceof MerchantActivity) {
                ((MerchantActivity) getActivity()).findViewById(R.id.bottom_navigation).findViewById(R.id.nav_merchant_home).performClick();
            }
        });

        llProfile.setOnClickListener(v -> {
            showUserInfoDialog();
        });

        llCart.setOnClickListener(v -> {
            // 跳转到购物车页面
            if (currentUser != null) {
                Intent intent = new Intent(requireContext(), CartActivity.class);
                startActivity(intent);
            } else {
                Toast.makeText(requireContext(), "请先登录", Toast.LENGTH_SHORT).show();
            }
        });

        llOrders.setOnClickListener(v -> {
            // 跳转到订单页面
            if (currentUser != null) {
                Intent intent = new Intent(requireContext(), OrderActivity.class);
                startActivity(intent);
            } else {
                Toast.makeText(requireContext(), "请先登录", Toast.LENGTH_SHORT).show();
            }
        });

        llSettings.setOnClickListener(v -> {
            showSettingsDialog();
        });
    }

    private void showUserInfoDialog() {
        if (currentUser != null) {
            String info = "用户信息：\n" +
                    "用户名：" + currentUser.getUsername() + "\n" +
                    "手机号：" + currentUser.getPhone() + "\n" +
                    "角色：" + currentUser.getRoleText();
            if (currentUser.isMerchant() && currentUser.getShopName() != null) {
                info += "\n店铺：" + currentUser.getShopName();
            }
            
            new android.app.AlertDialog.Builder(requireContext())
                    .setTitle("个人信息")
                    .setMessage(info)
                    .setPositiveButton("确定", null)
                    .show();
        }
    }

    private void showCartInfo() {
        if (currentUser != null) {
            // 获取购物车数量
            int cartCount = databaseHelper.getCartByUserId(currentUser.getId()).size();
            String message = "您的购物车中有 " + cartCount + " 件商品";
            Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(requireContext(), "请先登录", Toast.LENGTH_SHORT).show();
        }
    }

    private void showOrdersInfo() {
        if (currentUser != null) {
            // 获取订单数量
            int orderCount = databaseHelper.getOrdersByUserId(currentUser.getId()).size();
            String message = "您共有 " + orderCount + " 个订单";
            Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(requireContext(), "请先登录", Toast.LENGTH_SHORT).show();
        }
    }

    private void showSettingsDialog() {
        String[] items = {"修改密码", "清空购物车", "退出登录"};
        new android.app.AlertDialog.Builder(requireContext())
                .setTitle("设置")
                .setItems(items, (dialog, which) -> {
                    switch (which) {
                        case 0:
                            Toast.makeText(requireContext(), "修改密码功能开发中...", Toast.LENGTH_SHORT).show();
                            break;
                        case 1:
                            clearCart();
                            break;
                        case 2:
                            logout();
                            break;
                    }
                })
                .show();
    }

    private void clearCart() {
        if (currentUser != null) {
            boolean result = databaseHelper.clearCart(currentUser.getId());
            if (result) {
                Toast.makeText(requireContext(), "购物车已清空", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(requireContext(), "清空购物车失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void logout() {
        new android.app.AlertDialog.Builder(requireContext())
                .setTitle("退出登录")
                .setMessage("确定要退出登录吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    performLogout();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void performLogout() {
        try {
            String username = currentUser != null ? currentUser.getUsername() : "用户";
            preferenceManager.clearUserLogin();
            
            Intent intent = new Intent(requireContext(), LoginActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            intent.putExtra("fromLogout", true);
            intent.putExtra("logoutMessage", "再见，" + username + "！");
            startActivity(intent);
            
            if (getActivity() != null) {
                getActivity().finish();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(requireContext(), "退出登录失败，请重试", Toast.LENGTH_SHORT).show();
        }
    }
} 